#coding=utf8
__author__ = 'alex'
import logging
from flask import Blueprint, render_template, abort, g, request, redirect, url_for, session, flash
from models import *
from biz import *
from utils import *

admin = Blueprint('admin', __name__,template_folder='templates',url_prefix='/admin')

@admin.route("/login")
def login():
    return render_template("login.html",**locals())

@admin.route("/login", methods=["POST"])
def check_login():
    name = request.form.get("name")
    password = request.form.get("password")

    try:
        if manager(name).verify(password):
            session["user_name"]=name
            add_success(u"登陆成功")
        else:
            add_error(u"用户名秘密不正确")
            return redirect(url_for("admin.login"))
    except Exception, e:
        add_error(u"用户名秘密不正确")
        logging.error(print_debug(e))
        return redirect(url_for("admin.login"))
    return redirect(url_for("admin.index"))




@admin.app_template_filter(name="menu")
def menu(txt):
    catalogs = top_level()
    return render_template("include/menu.html",**locals())

@admin.app_template_filter(name="date")
def format_date(dt):
    return u"%s年%s月%s日"%(dt.year,dt.month,dt.day)

@admin.route("")
def index():
    return render_template("admin_index.html",**locals())

@admin.route("/catalog")
def catalog_manage():
    catalog = catalog_text()
    return render_template("manage_catalogs.html", **locals())

@admin.route("/catalog", methods = ["POST"])
def catalog_sync():
    txt = request.form.get("txt")
    try:
        sync_catalogs(0,txt)
        add_success(u"更新成功")
    except BizException, e:
        add_error(e.message)
    except Exception, e:
        add_error(u"未知异常")
        g.db.rollback()
        logging.error(print_debug(e))
    return redirect(url_for("admin.catalog_manage"))

@admin.route("/<catalog_id>/document")
def manage_document(catalog_id):
    catalog = g.db.query(Catalogs).get(catalog_id)
    cats = [cat.id for cat in catalog.all_childs]
    cats.append(catalog.id)
    documents = g.db.query(Document).filter(Document.catalog_id.in_(cats)).order_by(Document.id.desc())
    return render_template("manage_document.html",**locals())

@admin.route("/<catalog_id>/document/new")
def new_document(catalog_id):
    catalog = g.db.query(Catalogs).get(catalog_id)
    selected_catalog = session["selected_catalog"] if "selected_catalog" in session else None
    return render_template("add_new_document.html",**locals())

@admin.route("/<catalog_id>/document/new", methods = ["POST"])
def add_document(catalog_id):
    title = request.form.get("title")
    content = request.form.get("content")
    select_catalog_id = request.form.get("catalog")
    try:
        post_document(select_catalog_id,title,content,"alex")
        add_success(u"%s 添加成功"%title)
        session["selected_catalog"] = select_catalog_id
    except Exception, e:
        add_error(u"未知异常")
        logging.error(print_debug(e))
        g.db.rollback()
    return redirect(url_for("admin.new_document",catalog_id=catalog_id))

@admin.route("/<catalog_id>/document/<document_id>/edit")
def edit_document(catalog_id, document_id):
    catalog = g.db.query(Catalogs).get(catalog_id)
    document = g.db.query(Document).get(document_id)
    selected_catalog = g.db.query(Catalogs).get(document.catalog_id).id
    txt = txt_document(document_id)
    return render_template("edit_document.html",**locals())

@admin.route("/<catalog_id>/document/<document_id>/edit", methods=["POST"])
def update_document_act(catalog_id, document_id):
    document = g.db.query(Document).get(document_id)
    title = request.form.get("title")
    content = request.form.get("content")
    catalog_id_new = request.form.get("catalog")
    try:
        update_document(document, title, content, catalog_id_new)
        add_success(u"文档%s修改成功"%title)
    except Exception, e:
        add_error(u"未知异常")
        logging.error(print_debug(e))
        g.db.rollback()
    return redirect(url_for("admin.manage_document",catalog_id=catalog_id))